<template>
    <div>
        <div class="asset-overview">
            <h3 class="section-title">预估市值总资产(人民币)</h3>
            <h1 class="total-assets">{{ totals }} 万元</h1>
            <div class="daily-change">
                <span class="change-label">今日盈亏：</span>
                <span class="change-value" :class="numberClass">{{ totalProfit }} 万元</span>
                <span :class="numberClass">({{profitLoss}}%)</span>
                <span :class="numberClass">{{plusMinus}}</span>
            </div>
        </div>
        <div id="smoothedLineContainer" class="smoothedLineContainerClass"></div>
        <div class="time-buttons">
            <button
                v-for="range in ranges"
                :key="range"
                @click="changeTimeRange(range)"
                :class="{ active: activeRange === range }"
            >
                {{ range }}天
            </button>
        </div>
    </div>
</template>

<script setup>
import * as echarts from 'echarts';
import {TooltipComponent, GridComponent} from 'echarts/components';
import {LineChart} from 'echarts/charts';
import {UniversalTransition} from 'echarts/features';
import {CanvasRenderer} from 'echarts/renderers';
import {onMounted, ref, computed} from 'vue';
import {getCharts} from "@/api/index";

echarts.use([TooltipComponent, GridComponent, LineChart, CanvasRenderer, UniversalTransition]);

let chartInstance = null;
const totals = ref(null)
const profitLoss = ref(0)
const totalProfit = ref(0)
const plusMinus  = ref(0)
const dataX = ref([])
const totalProfitValueY = ref([])
const ranges = [7, 30, 180, 360]    // 按钮对应的天数
const activeRange = ref(7)          // 默认选中 7 天

const numberClass = computed(() => {
    return totalProfit.value.toString().startsWith('+') ? 'positive' : 'negative';
});

// 生成模拟数据
// const generateData = (days) => {
//     const dates = [];
//     const values = [];
//     const now = new Date();
//
//     for (let i = days - 1; i >= 0; i--) {
//         const date = new Date(now);
//         date.setDate(date.getDate() - i);
//         dates.push(`${date.getMonth() + 1}/${date.getDate()}`);
//         values.push(Math.floor(Math.random() * 500) + 800); // 生成800-1300之间的随机值
//     }
//
//     return {dates, values};
// };

// 切换时间范围的函数
const changeTimeRange = (days) => {
    activeRange.value = days
    const tmpdataX = dataX.value.slice(dataX.value.length - days)
    const tmptotalProfitValueY = totalProfitValueY.value.slice(totalProfitValueY.value.length - days)
    const option = {
        xAxis: {
            data: tmpdataX
        },
        series: [{
            data: tmptotalProfitValueY
        }],
    }
    chartInstance.setOption(option);
}

onMounted(() => {
    getCharts().then(response => {
        var totalProfitTemp = 0;
        totalProfitTemp = response.data.data.daily_profits[response.data.data.daily_profits.length - 1].total_profit - response.data.data.daily_profits[response.data.data.daily_profits.length - 2].total_profit;
        totalProfit.value = parseFloat(totalProfitTemp).toFixed(2);
        for (let i = 0; i < response.data.data.daily_profits.length; i++) {
            dataX.value.push(response.data.data.daily_profits[i].date)
            totalProfitValueY.value.push(response.data.data.daily_profits[i].total_profit)
        }
        const tmptotal = totalProfit.value
        var tmpprofitLoss;
        totals.value = response.data.data.totals[response.data.data.totals.length - 1]
        tmpprofitLoss = parseFloat(tmptotal) / parseFloat(totals.value) * 100;
        // 判断totals是否以"-"号开头
        if (totalProfit.value.startsWith('-')) {
            plusMinus.value = "▼";
            totalProfit.value = `${totalProfit.value}`;
            profitLoss.value = `${tmpprofitLoss.toFixed(2)}`;
        } else {
            plusMinus.value = "▲";
            totalProfit.value = `+${totalProfit.value}`;
            profitLoss.value = `+${tmpprofitLoss.toFixed(2)}`;
        }

        let data = [];
        let totalProfitValue = [];
        let temData = response.data.data.daily_profits.slice(response.data.data.daily_profits.length - 7);
        for (let i = 0; i < 7; i++) {
            data.push(temData[i].date);
            totalProfitValue.push(temData[i].total_profit);
        }
        const chartDom = document.getElementById('smoothedLineContainer');
        // 初始化图表
        chartInstance = echarts.init(chartDom);
        const option = {
            xAxis: {
                type: 'category',
                data: data
            },
            yAxis: {
                type: 'value',
            },
            series: [{
                itemStyle: {
                    color: '#bfa100',
                },
                lineStyle: {
                    color: '#ffe000',  // 线的颜色
                    width: 3           // 线的粗细
                },
                data: totalProfitValue,
                type: 'line',
                smooth: true,
                areaStyle: {
                    color: 'rgba(255,186,0,0.3)'
                }
            }
            ],
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross'
                }
            },
            // dataZoom: [
            //     {
            //         type: 'inside',
            //         start: 0,
            //         end: 100
            //     },
            //     {
            //         start: 0,
            //         end: 10
            //     }
            // ]
        }
        chartInstance.setOption(option);
    });

})
</script>

<style scoped>
.smoothedLineContainerClass{
    width: 1200px;
    height: 500px;
}
.time-buttons {
    display: flex;
    gap: 90px;
    margin-bottom: 20px;
    justify-content: center;
}

.time-buttons button {
    background: white;
    padding: 8px 16px;
    border: 1px solid transparent;
    border-radius: 200px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.3s;
}

.time-buttons button:hover {
    background-color: #eeeeee;
    border-color: #eeeeee;
}

.time-buttons button.active {
    background-color: #e0e0e0; /* 背景加深 */
    border-color: #e0e0e0;
}

/* 资产概览区域 */
.asset-overview {
    background-color: #fff;
    border-radius: 12px;
    padding-left: 10%;
    margin-bottom: 24px;
    font-size: 20px;
}

.change-value {
    font-weight: bold;
}

.positive {
    color: red;
}

.negative {
    color: green;
}

@media (max-width: 480px) {
    /* 进一步缩小尺寸 */
    .time-buttons {
        position: absolute;
        left: 50%;
        transform: translate(-50%, -50%);
        display: flex;
        gap: 40px;
        margin-top: -5%;
    }

    .time-buttons button {
        width: 50px;
        height: 25px;
        padding: 0px 0px;
        background: white;
    }
    .asset-overview{
        padding-left: 20px;
        margin-bottom: 0px;
        font-size: 14px;
    }
    .smoothedLineContainerClass{
        margin-top: -30px;
        width: 100%;
        height: 240px;
    }
}
</style>
